//
//  PersonalViewController.m
//  Arts1
//
//  Created by 孤星晨宇 on 15/9/18.
//  Copyright (c) 2015年 Arts1. All rights reserved.
//

#import "PersonalViewController.h"
#import "PrativeTextTableViewCell.h"
#import "PraviteImageTableViewCell.h"
#import <QuartzCore/QuartzCore.h>
#import <QuartzCore/CoreAnimation.h>
#import <MobileCoreServices/UTCoreTypes.h>
#import "AllHeader.h"
#import "PrivateSettingViewController.h"
#import "FinalTableViewCell.h"

// 设置个人信息
//#define kURL @"http://arts1.dlab.com.cn/app/changeinfo"
#define kURL @"http://arts1.cn/app/changeinfo"


// 上传用户头像
//#define faceURL @"http://arts1.dlab.com.cn/app/setface"
#define faceURL @"http://arts1.cn/app/setface"

@interface PersonalViewController ()<UITableViewDataSource, UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UITableView *mainTableview;

//选择头像的图片
@property (nonatomic ,strong) UIImage *photoImage;

// 左侧标题
@property (nonatomic, strong) NSArray *dataArr;


@property (nonatomic, strong) NSMutableArray *rightArr;

@property (nonatomic, strong) NSArray *parArr;

@end

@implementation PersonalViewController

- (NSMutableArray *)rightArr{
    if (!_rightArr) {
        self.rightArr = [NSMutableArray arrayWithObjects:@"",@"",@"",@"",@"",@"",@"",@"", nil];
    }
    return _rightArr;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.title = @"个人设置";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createMainTableView];
    _parArr = @[@"nickName",@"gender",@"mobile",@"job",@"Province",@"school",@"space"];
}

//请求数据
- (void)requestData
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    
    NSString *uid = dic[@"data"][@"uid"];
    
    NSString *key = dic[@"data"][@"key"];
    
    NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:@{@"uid":uid,@"key":key}];
    
    for (int i = 1; i < 8; i++) {
        NSString *str = [_rightArr objectAtIndex:i];
        if (![str isEqualToString:@""]) {
            [mdic setValue:_rightArr[i] forKeyPath:_parArr[i - 1]];
        }
    }
    

    NSDictionary *pardic = [mdic copy];
    
    [manage POST:kURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             // 请求返回的状态，当status = 1 时有数据
             NSInteger status = [dic[@"status"] integerValue];
             
             NSString *str = nil;
             
             switch (status) {
                 case 1:{
                     str = @"设置成功";
                     [self.navigationController popViewControllerAnimated:YES];
                 }
                     break;
                 case 0:
                     str = @"未知错误";
                     break;
                 case -1:
                     str = @"用户名或密码为空";
                     break;
                 case -2:
                     str = @"用户名或密码错误";
                     break;
                 case -3:
                     str = @"昵称不符合规范";
                     break;
                 default:
                     break;
             }

             [MBProgressHUD show:str icon:nil view:self.view];
             
             // 请求成功的时候调用这个block
             NSLog(@"数据请求--%@", dic);
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
}

//  上传用户头像
- (void)requestDataForUserImage
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"multipart/form-data"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //压缩图片
    NSData *imageData = UIImageJPEGRepresentation(_photoImage, 1.0);
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.png",str];
    
    
    //结束注册完成返回的两个值（uid和key）
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    
    NSString *uid = dic[@"data"][@"uid"];
    
    NSString *key = dic[@"data"][@"key"];
    
    NSDictionary *pardic = nil;
    
    
    if (uid && key)
    {
        pardic = @{@"uid":uid,
                   @"key":key};
    }
    
    [manage POST:faceURL parameters:pardic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
         
         if (imageData)
         {
             //设置图片的格式
             [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
         }
         
         
     } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject)
     {
         //请求成功
         NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
         // 请求返回的状态，当status = 1 时有数据
         NSInteger status = [dic[@"status"] integerValue];
         if (status == 1) {
//             [self requestData];
         }
         NSLog(@" 上传头像 返回数据 ： %@ ",dic);
         
     } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
         //请求失败
     }];
}


- (void)createMainTableView
{
    _dataArr = @[@"头像",@"名字",@"性别",@"手机号码",@"身份",@"省份",@"学校",@"画室",@"完成"];
    
    _mainTableview = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStyleGrouped)];
    _mainTableview.backgroundColor = kBackgroundColor;
    _mainTableview.delegate = self;
    _mainTableview.dataSource = self;
    _mainTableview.bounces = YES;
    [self.view addSubview:_mainTableview];
}

#pragma mark --- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 8;
    }
    return 1;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            return 70;
        }
        else
        {
            return 40;
        }
    }
    else
    {
        return 40;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            PraviteImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"imageSetingcell"];
            if (!cell)
            {
                cell = [[PraviteImageTableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"imageSetingcell"];
                
            }
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.leftlabel.text = _dataArr[indexPath.row];
            cell.photoImage = _photoImage;
            
            return cell;
        }
        else
        {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pravitecell"];
            if (!cell)
            {
                cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"pravitecell"];
                 cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.textLabel.textAlignment = NSTextAlignmentLeft;
                cell.textLabel.textColor = lFONTCOLOR;
                cell.detailTextLabel.textAlignment = NSTextAlignmentRight;
            }
           
            cell.textLabel.text = _dataArr[indexPath.row];
            cell.detailTextLabel.text = _rightArr[indexPath.row];
            
            return cell;
        }
    }
    else
    {
        FinalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"wancheng"];
        
        if (cell == nil)
        {
            cell = [[FinalTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"wancheng"];
             __weak PersonalViewController *wPersonVC = self;
            cell.finishMessageBlock = ^(){
                [wPersonVC requestDataForUserImage];
                [wPersonVC requestData];
            };
        }
        cell.textLabel.text = @"完成";
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取消选中的状态
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 0){
        if (indexPath.row == 0){
            
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self shootPiicturePrVideo];
            }];
            UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self selectExistingPictureOrVideo];
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:cameraAction];
            [alertController addAction:photoAction];
            [self presentViewController:alertController animated:YES completion:nil];
        } else {
            PrivateSettingViewController *pSettingVC = [[PrivateSettingViewController alloc] init];
            pSettingVC.str = _dataArr[indexPath.row];
            pSettingVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:pSettingVC animated:YES];
            pSettingVC.hidesBottomBarWhenPushed = NO;
            __weak PersonalViewController *wPersonVC = self;
            pSettingVC.privateSettingBlock = ^(NSString *string){
                [wPersonVC.rightArr replaceObjectAtIndex:indexPath.row withObject:string];
                [wPersonVC.mainTableview reloadData];
            };
            
        }
    }

}

//从相机上选择
- (void)shootPiicturePrVideo
{
    [self getMediaFromSource:UIImagePickerControllerSourceTypeCamera];
}

//从相册中选择
- (void)selectExistingPictureOrVideo
{
    [self getMediaFromSource:UIImagePickerControllerSourceTypePhotoLibrary];
}

//用户选中图片后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    //获得编辑过的图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    _photoImage = image;
    
    [_mainTableview reloadData];
    //如果不选择的话，可以返回原来的页面
    [picker dismissViewControllerAnimated:YES completion:^{
    
    }];
}
// 用户选择取消
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //如果不选择的话，可以返回原来的页面
    [picker dismissViewControllerAnimated:NO completion:nil];
    
}
//根据用户选取的类型(相册或者相机)来判断当前状态是否支持该功能
-(void)getMediaFromSource:(UIImagePickerControllerSourceType)sourceType
{
    NSArray *mediatypes = [UIImagePickerController availableMediaTypesForSourceType:sourceType];
    
    if([UIImagePickerController isSourceTypeAvailable:sourceType] &&[mediatypes count]>0)
    {
        NSArray *mediatypes = [UIImagePickerController availableMediaTypesForSourceType:sourceType];
        
        UIImagePickerController *picker=[[UIImagePickerController alloc] init];
        
        picker.mediaTypes = mediatypes;
        
        picker.delegate = self;
        
        picker.allowsEditing = YES;
        
        picker.sourceType = sourceType;
        
        NSString *requiredmediatype = (NSString *)kUTTypeImage;
        
        NSArray *arrmediatypes = [NSArray arrayWithObject:requiredmediatype];
        
        [picker setMediaTypes:arrmediatypes];
        
        [self presentViewController:picker animated:YES completion:^{
            
        }];
    }
    else
    {
        //如果不支持拍摄功能就弹出提示
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"错误信息!" message:@"当前设备不支持拍摄功能" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
